import axios from 'axios';

const inst = axios.create({
  // 禁用IE缓存
  headers: {
    'If-Modified-Since': 0,
    'Cache-Control': 'no-cache'
  },
})

function getQueryString(obj) {
  const keys = Object.keys(obj);
  const result = '?';
  keys.forEach((item, index) => {
    result += `${item}=${obj[item]}${index === keys.length - 1 ? '' : '&'}`
  })

  return result;
}

inst.interceptors.request.use(config => {
  const {url, data, method} = config;

  // 根据请求方式格式化get的请求参数
  const resultUrl = method === 'get' ? `${url}${getQueryString(data)}` : url;

  return {
    ...config,
    url: resultUrl
  }
})

// 如果有重复的请求需要进行取消
const cancelableRequests = {};

inst.interceptors.request.use(config => {
  // 默认开启自动取消
  const {url, autoCancel = true} = config;
  let cancelToken = null;

  if (autoCancel) {
    // 如果又来了一个跟之前一样的请求
    if (cancelableRequests[url]) {
      // 执行取消请求的操作
      cancelableRequests[url]();
    }
    const source = axios.CancelToken.source();
    cancelableRequests[url] = function () {
      source.cancel();
      delete cancelableRequests[url];
    }
    cancelToken = source.token;
  }

  return {
    ...config,
    cancelToken
  }
})

// 登录操作
let loginFlag;
// 同时只能执行一个登录操作
const loginFn = (params, msg) => {
  if (loginFlag) return;
  loginFlag = true;
  axios.post('/api/login', params).then((res) => {
    if (res.data?.code === 200) {
      alert(`登录成功 - ${msg}`)
      localStorage.setItem('user_info', res.data?.data?.['user_info'])
      localStorage.setItem('Expires', res.data?.data?.['Expires'])
      document.cookie += `${res.data?.data?.['user_id']};`
      window.location = '/home'
      loginFlag = false;
    } else {
      alert('登录失败');
      window.location.reload();
      loginFlag = false;
    }
  })
}

function removeCookie (key) {
  const cookieArr = window.cookie.split(';')
  // ['user_id=123']
  const resultArr = cookieArr?.filter(item => item.split('=')[0] !== key);
  window.cookie = resultArr.join(';')
}

// 登出操作
let logoutFlag;
// 同时只能执行一个登出操作
const logoutFn = (msg) => {
  if (logoutFlag) return;
  logoutFlag = true;
  axios.get('/api/logout').then((res) => {
    if (res.data?.code === 200) {
      alert(`登出成功 - ${msg}`);
      localStorage.removeItem('user_info');
      localStorage.removeItem('Expires');
      removeCookie('user_id')
      window.location = '/login'
    } else {
      alert('登出失败')
    }
  })
}

inst.interceptors.request.use(config => {
  const {cookie} = config;
  if (!cookie.split(';').some(item => item.split('=')[0] === 'user_id') && window.location.pathname !== '/login') {
    alert('用户未登录，请先登录')
    logoutFn();
  }
  const lastTime = new Date(Number(localStorage.getItem('Expires'))).getTime();
  const now = new Date().getTime();
  // 登录guoqi
  if (now > lastTime && window.location.pathname !== '/login') {
    alert('登录过期，请重新登录')
    logoutFn();
  }
  return config;
})

inst.CancelToken = axios.CancelToken;
inst._axios = axios;

export default inst;